
//---------------------------------------------------------------------------
#include "pg1_engine.h"
//---------------------------------------------------------------------------
#include "rendering/pg1_window.h"
#include "rendering/pg1_renderer.h"
#include "game/pg1_game.h"
#include "input/pg1_directinput.h"
#include "animation/pg1_timer.h"
//---------------------------------------------------------------------------
#include <sstream>
//---------------------------------------------------------------------------
using namespace pg1;
//---------------------------------------------------------------------------
Engine::Engine (HINSTANCE hInstance, unsigned int uiWidth, unsigned int uiHeight)
:
m_hInstance(hInstance),
m_uiWidth(uiWidth),
m_uiHeight(uiHeight),
m_pkWindow( new Window() ),
m_pkRenderer( new Renderer() ),
m_pkGame(NULL),
m_pkInput( new DirectInput() ),
m_pkTimer( new Timer() )
{
	// nothing to do
}
//---------------------------------------------------------------------------
Engine::~Engine ()
{
	delete m_pkTimer;
	m_pkTimer = NULL;

	delete m_pkInput;
	m_pkInput = NULL;

	delete m_pkRenderer;
	m_pkRenderer = NULL;

	delete m_pkWindow;
	m_pkWindow = NULL;
}
//---------------------------------------------------------------------------
bool Engine::init ()
{
	// create window
	if( !m_pkWindow->create(m_hInstance, m_uiWidth, m_uiHeight) )
	{
		return false;
	}

	// init rendering system
	if( !m_pkRenderer->init( m_pkWindow->hwnd() ) )
	{
		return false;
	}

	// init input
	if( !m_pkInput->init( m_hInstance, m_pkWindow->hwnd() ) )
	{
		return false;
	}

	return true;
}
//---------------------------------------------------------------------------
void Engine::run ()
{
	if(!m_pkGame)
	{
		return;
	}

	// init game
	if( !m_pkGame->init(*m_pkRenderer) )
	{
		return;
	}

	// first timer measure
	m_pkTimer->firstMeasure();
	
	// frame loop
	MSG kMsg;
	while( !m_pkGame->isDone() )
	{
		// update timer
		m_pkTimer->measure();

		// update FPSs
		static std::stringstream kSS;
		kSS.str("");
		kSS << "PG1 Engine (" << m_pkTimer->fps() << " FPS)";
		m_pkWindow->setTitle( kSS.str() );

		// update input
		m_pkInput->reacquire();

		// render frame
		m_pkRenderer->beginFrame();

		m_pkGame->frame(*m_pkRenderer, *m_pkInput, *m_pkTimer);

		m_pkRenderer->endFrame();

		if( PeekMessage(&kMsg, NULL, 0, 0, PM_REMOVE) )
		{
			// check if we have to exit the game
			switch(kMsg.message)
			{
				case WM_QUIT:
				{
					m_pkGame->setDone(true);
					break;
				}
			}

			TranslateMessage(&kMsg);
			DispatchMessage(&kMsg);
		}
	}

	// deinitialization
	m_pkGame->deinit();
}
//---------------------------------------------------------------------------
